package com.umfwechat.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class SaasPropertyUtil {
	
	/** 
	 * 将一个类查询方式加入map
	 * 
	 */
	public static Map<String, String> javaBeanToMap(Object obj) throws Exception{
		Map<String, String> map = new HashMap<String, String>();  
		if(obj==null){
			return null;
		}
		Field[] fields = obj.getClass().getDeclaredFields();
		for(Field field : fields){
			String fieldName =  field.getName();
			if(!"serialVersionUID".equals(fieldName)&&getValueByFieldName(fieldName,obj)!=null){
				map.put(fieldName,  String.valueOf(getValueByFieldName(fieldName,obj)));
			}
			else {
				map.put(fieldName, "");
			}
		}
		return map;
	}
	
	/** 
	 * 将一个类查询方式加入map
	 * 
	 */
	public static Map<String, Object> javaBeanToMapO(Object obj) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();  
		if(obj==null){
			return null;
		}
		Field[] fields = obj.getClass().getDeclaredFields();
		for(Field field : fields){
			String fieldName = field.getName();
			if(!"serialVersionUID".equals(fieldName)&&getValueByFieldName(fieldName,obj)!=null){
				map.put(fieldName, getValueByFieldName(fieldName,obj));
			}
			else {
				map.put(fieldName, "");
			}
		}
		return map;
	}
	
	
	
	/** 
	 * 根据属性名获取该类此属性的值 
	 * @param fieldName 
	 * @param object 
	 * @return 
	 */  
	private static Object getValueByFieldName(String fieldName,Object object) throws Exception{
		String firstLetter=fieldName.substring(0,1).toUpperCase();
		String getter = "get"+firstLetter+fieldName.substring(1);
		Method method = object.getClass().getMethod(getter, new Class[]{});
		Object value = method.invoke(object, new Object[] {});
		return value;
	}
}
